package com.benmei.weike.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.Charset;

public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static void main(String[] args) {

    }

    /**
     * http post 请求
     *
     * @param uri
     * @param body
     * @return
     */
    public static String httpPost(String uri, String body) {
        logger.info("uri ---->>" + uri);
        logger.info("body ---->> \n" + body + "\n");
        String responseBody = "";
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(uri);
        post.addRequestHeader("text/plain", "UTF-8");

        try {
            StringRequestEntity entity = new StringRequestEntity(body, null, null);
            post.setRequestEntity(entity);

            // Execute the method.
            int statusCode = client.executeMethod(post);

            logger.info("status code --->>" + statusCode);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed: " + post.getStatusLine());
            }

            // Read the response body.
            byte[] responseBodyB = post.getResponseBody();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            responseBody = new String(responseBodyB);
            logger.info("responseBody ---->>" + responseBody);

        } catch (HttpException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            // Release the connection.
            post.releaseConnection();
        }
        return responseBody;
    }

    public static String httpGet(String uri) {
        String body = "";
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(uri);
        HttpGet get = new HttpGet(uri);
        logger.info("执行请求： " + get.getURI());
        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);
            logger.info("状态码：" + statusCode);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed: " + method.getStatusLine());
            }

            // Read the response body.
            byte[] responseBody = method.getResponseBody();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            logger.info(new String(responseBody));

        } catch (HttpException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
        return body;
    }

    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
        URL url = null;
        HttpURLConnection conn = null;
        StringBuffer buffer = new StringBuffer();
        try {
            url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.connect();

            if (null != outputStr) {
                OutputStream outputStream = null;
                outputStream = conn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            InputStreamReader inputStreamReader = null;
            // 将返回的输入流转换成字符串
            InputStream inputStream = null;
            inputStream = conn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");

            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            logger.info("输出日志：" + str);
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            conn.disconnect();

        } catch (MalformedURLException e) {
            logger.error(e.getMessage(), e);
        } catch (ProtocolException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

        return buffer.toString();

    }


    /**
     * @param url 连接地址
     * @param js  参数列表(application/json数据格式)
     * @return
     * @throws
     */
    public static String PostJsonRequest(String url, JSONObject js) {
        //创建httpClient连接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建提交方式
        HttpPost post = new HttpPost(url);
        //存放响应参数
        UrlEncodedFormEntity formatEntity;
        String content = null;
        String postRequest = js.toString();
        StringEntity reqEntity = null;
        try {
            //用StringEntity对象包装请求体数据
            reqEntity = new StringEntity(postRequest);

            //设置请求头数据传输格式
            reqEntity.setContentType("application/json");

            //通过post请求将格式化过的实体放到post实体中
            post.setEntity(reqEntity);
            System.out.println("执行请求： " + post.getURI());
            //响应参数
            CloseableHttpResponse response = httpClient.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            if (statusCode == 200) {
                try {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        content = EntityUtils.toString(entity, "UTF-8");
                    }
                } finally {
                    response.close();
                }
            } else {
                System.out.println(statusCode + "wrong");
            }

        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        } catch (ClientProtocolException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error("关闭httpClient失败。" + e.getMessage(), e);
            }
        }
        return content;
    }

    public static String getRequest(String url) {
        //创建httpClient连接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建提交方式
        HttpGet get = new HttpGet(url);
        String content = "";
        try {
            System.out.println("执行请求： " + get.getURI());
            //响应参数
            CloseableHttpResponse response = httpClient.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();

            System.out.println(statusCode);
            if (statusCode == 200) {
                try {
                    HttpEntity entity = response.getEntity();
                    content = EntityUtils.toString(entity, "UTF-8");
                    if (entity != null) {
                        System.out.println("响应内容: " + content);
                    }
                } finally {
                    response.close();
                }
            } else {
                System.out.println(statusCode + "错误");
            }

        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        } catch (ClientProtocolException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error("关闭httpClient失败。" + e.getMessage(), e);
            }
        }
        return content;
    }
}
